﻿using System;
using System . Collections . Generic;
using System . IO;
using System . Linq;
using System . Runtime . InteropServices . WindowsRuntime;
using System . Threading . Tasks;
using Windows . Foundation;
using Windows . Foundation . Collections;
using Windows . UI . Xaml;
using Windows . UI . Xaml . Controls;
using Windows . UI . Xaml . Controls . Primitives;
using Windows . UI . Xaml . Data;
using Windows . UI . Xaml . Input;
using Windows . UI . Xaml . Media;
using Windows . UI . Xaml . Navigation;
using WenceyWang . RichMan4L . App . Pages . Controls;

namespace WenceyWang . RichMan4L . App . Pages
{
	/// <summary>
	/// 提供加载动画的页
	/// </summary>
	public sealed partial class LoadingPage : Page
	{
		GameSaying currentSaying;

		SayingPresenter currentPrenster;

		SayingPresenter toBeDeletePrenster;

		Task taskToWait;

		Action actionToDoNext;

		DispatcherTimer Timer;

		public LoadingPage ( )
		{
			this . InitializeComponent ( );
			this . Loaded += LoadingPage_Loaded;
		}

		private void LoadingPage_Loaded ( object sender , RoutedEventArgs e )
		{
			Timer = new DispatcherTimer ( );
			Timer . Interval = UpdateSaying ( );
			Timer . Tick += Timer_Tick;
		}

		private TimeSpan UpdateSaying ( )
		{
			if ( toBeDeletePrenster != null )
			{
				SayingPresentGrid . Children . Remove ( toBeDeletePrenster );
			}
			currentSaying = GameSaying . GetSaying ( );
			SayingPresenter toShow = new SayingPresenter ( currentSaying );
			SayingPresentGrid . Children . Add ( toShow );
			VisualStateManager . GoToState ( currentPrenster , "Hide" , true );
			toBeDeletePrenster = currentPrenster;
			currentPrenster = toShow;
			VisualStateManager . GoToState ( currentPrenster , "Show" , true );
			TimeSpan timeSpan = TimeSpan . FromSeconds ( currentSaying . Context . Length * 0.1 + 1.5 );
			return timeSpan;
		}

		private void Timer_Tick ( object sender , object e )
		{
			if ( taskToWait . IsFaulted || taskToWait . IsCanceled )
			{
				throw taskToWait . Exception;
			}
			if ( taskToWait . IsCompleted )
			{
				
			}
			Timer . Interval = UpdateSaying ( );

		}

		protected override void OnNavigatedFrom ( NavigationEventArgs e )
		{
			if ( e . Parameter != null && e . Parameter is Tuple<Task , Action> && ( e . Parameter as Tuple<Task , Action> ) . Item1 != null && ( e . Parameter as Tuple<Task , Action> ) . Item2 != null )
			{
				taskToWait = ( e . Parameter as Tuple<Task , Action> ) . Item1;
				actionToDoNext = ( e . Parameter as Tuple<Task , Action> ) . Item2;
			}
			else
			{
				throw new ArgumentException ( "Invalid Loading Parameter" );
			}

			base . OnNavigatedFrom ( e );
		}
	}
}
